package app.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.filechooser.FileFilter;

public class FileUtilities extends FileFilter implements Runnable {
	private OutputStream out;
	private InputStream in;
	private String[] acceptExtention = null;
	private String describeFile;

	/**
	 * @param acceptExtention	Example: {"mp3", "wav"};
	 * @param describeFile		Example: "media file"
	 */
	public FileUtilities(String[] acceptExtention, String describeFile) {
		this.acceptExtention = acceptExtention;
		this.describeFile = describeFile;
		
		if(describeFile == null) {
			this.describeFile = "Select file.";
		}
	}

	public boolean copyFile(File source, File target) {
		if (!source.exists()) {
			return false;
		}
		try {
			this.in = new FileInputStream(source);
			this.out = new FileOutputStream(target);

			Thread t = new Thread(this);
			t.start();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}

	public String getExtension(File f) {
		String str = f.getName();
		int index = str.lastIndexOf('.');
	
		if (index > 0 && index < str.length() - 1) {
			return str.substring(index + 1).toLowerCase();
		}
	
		return null;
	}

	public void run() {
		if (in == null || out == null) {
			System.err
					.println("Error in construct. -- " + getClass().getName());
			return;
		}
		byte[] buffer = new byte[1024];
		int bytesRead;
		try {
			bytesRead = in.read(buffer);
			while (bytesRead >= 0) {
				out.write(buffer, 0, bytesRead);
				bytesRead = in.read(buffer);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public boolean accept(File f) {
		if (acceptExtention == null || acceptExtention[0] == null || f == null) {
			return false;
		}

		String strExtention = getExtension(f);
		if (f.isDirectory() || strExtention == null) {
			return true;
		} else {
			for (String str : acceptExtention) {
				if (str.equalsIgnoreCase(strExtention)) {
					return true;
				}
			}
		}

		return false;
	}

	@Override
	public String getDescription() {
		return describeFile;
	}
}
